using EasyElasticLogger.NETFramework.ES.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EasyElasticLogger.NETFramework.ES.Indexing
{
    /// <summary>
    /// 索引管理器，负责生成索引名称
    /// </summary>
    public static class IndexManager
    {
        /// <summary>
        /// 根据配置和时间生成索引名称
        /// </summary>
        /// <param name="config">日志记录器配置</param>
        /// <param name="timestamp">时间戳</param>
        /// <returns>索引名称</returns>
        public static string GenerateIndexName(LoggerConfiguration config, DateTime timestamp)
        {
            if (config == null)
                throw new ArgumentNullException(nameof(config));

            switch (config.IndexStrategy)
            {
                case IndexStrategy.Fixed:
                    return GetFixedIndexName(config);
                
                case IndexStrategy.DailyRolling:
                    return GetDailyRollingIndexName(config, timestamp);
                
                default:
                    // 默认使用按日期滚动
                    return GetDailyRollingIndexName(config, timestamp);
            }
        }

        /// <summary>
        /// 获取固定索引名称
        /// </summary>
        /// <param name="config">日志记录器配置</param>
        /// <returns>固定索引名称</returns>
        private static string GetFixedIndexName(LoggerConfiguration config)
        {
            if (string.IsNullOrEmpty(config.FixedIndexName))
            {
                // 如果未指定固定索引名称，则使用索引前缀
                return config.IndexPrefix ?? "app-log";
            }
            
            return config.FixedIndexName;
        }

        /// <summary>
        /// 获取按日期滚动的索引名称
        /// </summary>
        /// <param name="config">日志记录器配置</param>
        /// <param name="timestamp">时间戳</param>
        /// <returns>按日期滚动的索引名称</returns>
        private static string GetDailyRollingIndexName(LoggerConfiguration config, DateTime timestamp)
        {
            var prefix = config.IndexPrefix ?? "app-log";
            return $"{prefix}-{timestamp:yyyy.MM.dd}";
        }
    }
}